<template>
  <div class="p-6">
    <div class="flex justify-between items-center mb-6">
      <h2 class="text-2xl font-bold text-gray-900">设备管理</h2>
      <button
        @click="$router.push('/equipment/form')"
        class="btn btn-primary"
      >
        <PlusIcon class="w-5 h-5 mr-2" />
        设备登记
      </button>
    </div>
    
    <!-- 搜索栏 -->
    <div class="card mb-6">
      <div class="card-body">
        <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
          <div class="md:col-span-2">
            <label class="form-label">智能搜索</label>
            <input
              v-model="searchForm.keyword"
              type="text"
              class="form-input"
              placeholder="请输入设备编号、名称、规格、厂家进行搜索"
            />
          </div>
          <div>
            <label class="form-label">设备类别</label>
            <select v-model="searchForm.category" class="form-input">
              <option value="">请选择类别</option>
              <option value="计算机设备">计算机设备</option>
              <option value="实验仪器">实验仪器</option>
              <option value="化学仪器">化学仪器</option>
              <option value="生物仪器">生物仪器</option>
              <option value="其他设备">其他设备</option>
            </select>
          </div>
          <div>
            <label class="form-label">设备状态</label>
            <select v-model="searchForm.status" class="form-input">
              <option value="">请选择状态</option>
              <option value="NORMAL">正常</option>
              <option value="BORROWED">借用中</option>
              <option value="REPAIRING">维修中</option>
              <option value="SCRAPPED">已报废</option>
            </select>
          </div>
        </div>
        <div class="flex justify-end space-x-2 mt-4">
          <button @click="handleSearch" class="btn btn-primary">搜索</button>
          <button @click="handleReset" class="btn btn-secondary">重置</button>
        </div>
      </div>
    </div>
    
    <!-- 设备列表 -->
    <div class="card">
      <div class="card-body">
        <div v-if="loading" class="text-center py-8">
          <div class="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-primary-600"></div>
          <p class="mt-2 text-gray-600">加载中...</p>
        </div>
        
        <div v-else class="overflow-x-auto">
          <table class="table">
            <thead>
              <tr>
                <th>设备编号</th>
                <th>设备名称</th>
                <th>设备类别</th>
                <th>规格</th>
                <th>数量</th>
                <th>单价</th>
                <th>生产厂家</th>
                <th>购置日期</th>
                <th>状态</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="equipment in equipments" :key="equipment.id">
                <td>{{ equipment.code }}</td>
                <td>{{ equipment.name }}</td>
                <td>{{ equipment.category }}</td>
                <td class="max-w-xs truncate">{{ equipment.specification }}</td>
                <td>{{ equipment.quantity }}</td>
                <td>¥{{ equipment.unitPrice }}</td>
                <td>{{ equipment.manufacturer }}</td>
                <td>{{ equipment.purchaseDate }}</td>
                <td>
                  <span :class="getStatusClass(equipment.status)">
                    {{ getStatusText(equipment.status) }}
                  </span>
                </td>
                <td>
                  <div class="flex space-x-2">
                    <button
                      @click="viewDetail(equipment)"
                      class="text-primary-600 hover:text-primary-700 text-sm"
                    >
                      查看
                    </button>
                    <button
                      @click="editEquipment(equipment)"
                      class="text-primary-600 hover:text-primary-700 text-sm"
                    >
                      编辑
                    </button>
                    <button
                      v-if="equipment.status === 'NORMAL'"
                      @click="borrowEquipment(equipment)"
                      class="text-green-600 hover:text-green-700 text-sm"
                    >
                      借用
                    </button>
                  </div>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
        
        <!-- 分页 -->
        <div class="flex justify-between items-center mt-6">
          <div class="text-sm text-gray-600">
            共 {{ pagination.total }} 条记录
          </div>
          <div class="flex items-center space-x-2">
            <select
              v-model="pagination.size"
              @change="handleSizeChange"
              class="form-input w-20"
            >
              <option value="10">10</option>
              <option value="20">20</option>
              <option value="50">50</option>
              <option value="100">100</option>
            </select>
            <span class="text-sm text-gray-600">条/页</span>
            <div class="flex space-x-1">
              <button
                @click="handleCurrentChange(pagination.current - 1)"
                :disabled="pagination.current <= 1"
                class="px-3 py-1 text-sm border border-gray-300 rounded hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
              >
                上一页
              </button>
              
              <!-- 页码按钮 -->
              <template v-for="page in getPageNumbers()" :key="page">
                <button
                  v-if="page !== '...'"
                  @click="handleCurrentChange(page)"
                  :class="[
                    'px-3 py-1 text-sm border rounded',
                    page === pagination.current
                      ? 'bg-blue-500 text-white border-blue-500'
                      : 'border-gray-300 hover:bg-gray-50'
                  ]"
                >
                  {{ page }}
                </button>
                <span v-else class="px-3 py-1 text-sm text-gray-500">...</span>
              </template>
              
              <button
                @click="handleCurrentChange(pagination.current + 1)"
                :disabled="pagination.current >= Math.ceil(pagination.total / pagination.size)"
                class="px-3 py-1 text-sm border border-gray-300 rounded hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
              >
                下一页
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { PlusIcon } from '@heroicons/vue/24/outline'
import request from '@/utils/request'

const router = useRouter()

const equipments = ref([])
const loading = ref(false)

const searchForm = reactive({
  keyword: '',
  category: '',
  status: ''
})

const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 获取状态样式类
const getStatusClass = (status) => {
  const statusClasses = {
    'NORMAL': 'inline-flex px-2 py-1 text-xs font-semibold rounded-full bg-green-100 text-green-800',
    'BORROWED': 'inline-flex px-2 py-1 text-xs font-semibold rounded-full bg-yellow-100 text-yellow-800',
    'REPAIRING': 'inline-flex px-2 py-1 text-xs font-semibold rounded-full bg-blue-100 text-blue-800',
    'SCRAPPED': 'inline-flex px-2 py-1 text-xs font-semibold rounded-full bg-red-100 text-red-800'
  }
  return statusClasses[status] || 'inline-flex px-2 py-1 text-xs font-semibold rounded-full bg-gray-100 text-gray-800'
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    'NORMAL': '正常',
    'BORROWED': '借用中',
    'REPAIRING': '维修中',
    'SCRAPPED': '已报废'
  }
  return statusMap[status] || status
}

// 查看详情
const viewDetail = (equipment) => {
  router.push(`/equipment/detail/${equipment.id}`)
}

// 编辑设备
const editEquipment = (equipment) => {
  router.push(`/equipment/form/${equipment.id}`)
}

// 借用设备
const borrowEquipment = (equipment) => {
  router.push(`/equipment-borrow/form?equipmentId=${equipment.id}`)
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  loadEquipments()
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    keyword: '',
    category: '',
    status: ''
  })
  pagination.current = 1
  loadEquipments()
}

// 分页大小改变
const handleSizeChange = () => {
  pagination.current = 1
  loadEquipments()
}

// 当前页改变
const handleCurrentChange = (current) => {
  pagination.current = current
  loadEquipments()
}

// 生成页码数组
const getPageNumbers = () => {
  const totalPages = Math.ceil(pagination.total / pagination.size)
  const current = pagination.current
  const pages = []
  
  if (totalPages <= 7) {
    // 总页数少于等于7页，显示所有页码
    for (let i = 1; i <= totalPages; i++) {
      pages.push(i)
    }
  } else {
    // 总页数大于7页，显示省略号
    if (current <= 4) {
      // 当前页在前4页
      for (let i = 1; i <= 5; i++) {
        pages.push(i)
      }
      pages.push('...')
      pages.push(totalPages)
    } else if (current >= totalPages - 3) {
      // 当前页在后4页
      pages.push(1)
      pages.push('...')
      for (let i = totalPages - 4; i <= totalPages; i++) {
        pages.push(i)
      }
    } else {
      // 当前页在中间
      pages.push(1)
      pages.push('...')
      for (let i = current - 1; i <= current + 1; i++) {
        pages.push(i)
      }
      pages.push('...')
      pages.push(totalPages)
    }
  }
  
  return pages
}

// 加载设备列表
const loadEquipments = async () => {
  try {
    loading.value = true
    const params = {
      pageNum: pagination.current,
      pageSize: pagination.size,
      category: searchForm.category,
      status: searchForm.status
    }
    
    // 如果有关键词，同时搜索名称和编号
    if (searchForm.keyword) {
      params.name = searchForm.keyword
      params.code = searchForm.keyword
    }
    
    const response = await request.get('/equipment/list', { params })
    equipments.value = response.data.records
    pagination.total = response.data.total
  } catch (error) {
    console.error('加载设备列表失败:', error)
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  loadEquipments()
})
</script>